package com.etc.doctor.service.impl;


import cn.hutool.json.JSONUtil;
import com.etc.doctor.entity.Position;
import com.etc.doctor.mapper.PositionMapper;
import com.etc.doctor.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.etc.common.utils.RedisConstants.CACHE_POSITION;

@Service
public class PositionServiceImpl implements PositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<Position> queryAll() {
        Boolean isExist = stringRedisTemplate.hasKey(CACHE_POSITION);
        //判断redis中是否有缓存
        if (isExist){
            List<String> json=stringRedisTemplate.opsForList().range(CACHE_POSITION,0,-1);
            //转化成list
            List<Position> list= JSONUtil.toList(json.toString(),Position.class);
            return list;
        }
        //没有缓存，查询数据库
        List<Position> list=positionMapper.queryAll();
        for(Position position:list){
            //转化成json
            String jsonStr= JSONUtil.toJsonStr(position);
            //写入redis
            stringRedisTemplate.opsForList().leftPush(CACHE_POSITION,jsonStr);
        }
        return list;
    }
}
